import dayjs from 'dayjs';
const formatTime = (date, template) => dayjs(date).format(template);

/**
 * 手机号码*加密函数
 * @param {string} phone 电话号
 * @returns
 */
const phoneEncryption = (phone) => {
  return phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2');
};
// 内置手机号正则字符串
const innerPhoneReg =
  '^1(?:3\\d|4[4-9]|5[0-35-9]|6[67]|7[0-8]|8\\d|9\\d)\\d{8}$';

/**
 * 手机号正则校验
 * @param phone 手机号
 * @param phoneReg 正则字符串
 * @returns true - 校验通过 false - 校验失败
 */
const phoneRegCheck = (phone) => {
  const phoneRegExp = new RegExp(innerPhoneReg);
  return phoneRegExp.test(phone);
};

/**
 * 生成uuid
 */
const wxuuid = function () {
  var s = [];
  var hexDigits = "0123456789abcdef";
  for (var i = 0; i < 36; i++) {
    s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
  }
  s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
  s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
  s[8] = s[13] = s[18] = s[23] = "-";
  var uuid = s.join("").replace("-","");
  return uuid
}
const DISABLEKEY = { 
  '0':'正常',
  '6':'违规',
  '7':'冻结',
  '8':'封禁',
}
const DISABLEKEYTOB = { 
  '0':'正常',
  '40003':'违规',
  '40002':'冻结',
  '40001':'封禁',
}

const USERVIEWTYPE = [
  '',
  'icon_vip_normal-16@3x.png',
  'icon_vip_month-16@3x.png',
  'icon_vip_quarter-16@3x.png',
  'icon_vip_year-24@3x.png',
  'icon_vip_tryout-16@3x.png',
  'icon_vip_week-16@3x.png'
]

// 防抖
function debounce(fn, interval) {
  console.log(fn);
  let timer;
  let delay = interval || 1000; // 间隔的时间，如果interval不传，则默认1秒
  return function () {
      let that = this;
      let args = arguments; // 保存此处的arguments，因为setTimeout是全局的，arguments不是防抖函数需要的。
      if (timer) {
          clearTimeout(timer);
      }
      timer = setTimeout(function () {
          fn.apply(that, args); // 用apply指向调用debounce的对象，相当于this.fn(args);
      }, delay);
  };
}
// 节流
function throttle(fn, gapTime) {
  if (gapTime == null || gapTime == undefined) {
      gapTime = 1500
  }
  let _lastTime = null
  // 返回新的函数
  return function () {
      let _nowTime = +new Date()
      if (_nowTime - _lastTime > gapTime || !_lastTime) {
          fn.apply(this, arguments) //将this和参数传给原函数
          _lastTime = _nowTime
      }
  }
}
const urlToObj = function(url) {
  let obj = {}
  let str = url.slice(url.indexOf('?') + 1)
  let arr = str.split('&')
  for (let j = arr.length, i = 0; i < j; i++) {
    let arr_temp = arr[i].split('=')
    obj[arr_temp[0]] = arr_temp[1]
  }
  return obj
}
module.exports = {
  urlToObj,
  DISABLEKEYTOB,
  formatTime,
  phoneRegCheck,
  phoneEncryption,
  wxuuid,
  DISABLEKEY,
  USERVIEWTYPE,
  debounce,
  throttle
}
